package com.winchain.chainbill.basic.charge.rx;

import com.shell.bee.base.utils.StringUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.winchain.chainbill.basic.charge.service.ValComService;
import com.winchain.chainbill.basic.charge.service.ValRetBizService;
import com.winchain.chainbill.basic.charge.vo.ValComVo;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillEvent;
import com.winchain.chainbill.bill.biz.transfer.vo.BillSplitEvent;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ValRetBizSaveSubscriber extends OnErrorNotImplementedSubscriber<BillEvent<CbDct>> {
	@Autowired
	private ValComService valComService;
	@Autowired
	private ValRetBizService valRetBizService;

	public void onApplicationEvent(BillEvent<CbDct> t) {
		CbDct cbDct = getDct(t);
		if ((cbDct == null) || (cbDct.getDctId() == null)) {
			return;
		}
		String finId = cbDct.getFinId();
		String grpId = t.getBill().getRec().getGrpId();
		ValComVo valCom = this.valComService.getDctValComVo(finId, grpId);
		if ((valCom != null) && ("1".equals(valCom.getValState()))) {
			if ("0".equals(valCom.getPayBy())) {
				return;
			}
			String dctDate = cbDct.getDctDate();
			String bizId = cbDct.getDctId();
			String bizType = "0";
			this.valRetBizService.saveServiceFee(bizId, bizType, dctDate, cbDct.getSerFee(), valCom);
		}
	}

	private CbDct getDct(BillEvent<CbDct> t) {
		CbDct cbDct = (CbDct) t.getBill().getSource();
		if ((t instanceof BillSplitEvent)) {
			BillSplitEvent<CbDct> event = (BillSplitEvent) t;
			List<Bill<CbDct>> bills = (List<Bill<CbDct>>) event.getChildren();
			for (Bill<CbDct> bill : bills) {
				cbDct = (CbDct) bill.getSource();
				if ((cbDct != null) && (StringUtil.notEmpty(cbDct.getDctId()))) {
					break;
				}
			}
		}
		return cbDct;
	}
}
